package com.elite.groovy.callback

import com.alibaba.fastjson.JSONObject
import com.elite.groovy.kh.CosFileUtils
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.FileUploadUtil
import com.wisdge.dataservice.Result
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: apiClinkRecord
 * @description: 天润录音调听API
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */

public class apiClinkRecord implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiClinkRecord.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        //获取所有参数名
        JSONObject Params_Json = new JSONObject();
        Enumeration ElementInfo = request.getParameterNames();
        while (ElementInfo.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) ElementInfo.nextElement();
            //再通过的方法来获取对应参数名的值
            log.debug("[调用请求信息]:" + parameterName + ": " + request.getParameter(parameterName));
            Params_Json.put(parameterName, request.getParameter(parameterName));
        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate def_jt = new JdbcTemplate(eliteBean.getDataSource());
        String outData = "";

        try {
            String MainUniqueId = request.getParameter("recordid");
            boolean isDownload = request.getParameter("d");

            String getRecordSQL = '''select recordFile from clink_list_uniqueid_record where uniqueId = ?''';
            List<Map<String, Object>> getRecordList = def_jt.queryForList(getRecordSQL, MainUniqueId);

            // 录音记录校验
            if (getRecordList.size() == 0) {
                outData = "apiClinkRecord HTTP请求调用错误，未检索到录音记录：" + getRecordList.toString();
                log.error(outData);
                return JSONObject.toJSONString(new Result(Result.ERROR, outData));
            }

            // 录音文件有效性校验
            String recordFile = getRecordList.get(0).get("recordFile");
            if (KHUtil.isNull(recordFile)) {
                outData = "apiClinkRecord HTTP请求调用错误，未检索到录音路劲：" + recordFile;
                log.error(outData);
                return JSONObject.toJSONString(new Result(Result.ERROR, outData));
            }

            // 处理录音文件地址(20062023/record/8008105/8008105-20230620172844-13732217786-2001--record-medias_2-1687253324.131789.mp3)
            String[] recordFiles = recordFile.split("-");
            String cosFilePath = recordFiles[1].substring(6, 8) + recordFiles[1].substring(4, 6) + recordFiles[1].substring(0, 4) + "/" + recordFiles[5] + "/" + recordFiles[0] + "/" + recordFile + ".mp3";
            log.debug("处理录音文件地址：" + cosFilePath);

            String localFilePath = KHDBConfig.getParamConfig(eliteBean, "TR-RecordPath") + "/" + recordFile + ".mp3";
            log.debug("本地录音文件地址：" + localFilePath);

            boolean downloadFlag = CosFileUtils.download("AKIDJTWowqY3L4gIrGVaR4TffPvCLLCrLdrx", "2veLzZbHsNtrmZECIMG0325D9zfKsQxO", "ap-shanghai", "dada-callvoice-mp3-1307278134", cosFilePath, localFilePath);

            if (downloadFlag) {
                String uploadPath = uploadNGS(eliteBean, localFilePath);

                String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "SYS-OuterDomain");
                DOMAIN = DOMAIN.endsWith("/") ? DOMAIN : DOMAIN + "/";
                String httpURL = DOMAIN + "ngs/fs/get?file=" + uploadPath;

                if (isDownload) {
                    httpURL = httpURL + "&d=true";
                }
                log.debug("录音调听完整地址:" + httpURL);
                response.sendRedirect(httpURL);
            } else {

                outData = "apiClinkRecord 文件处理异常：" + downloadFlag;
                log.error(outData);
                return JSONObject.toJSONString(new Result(Result.ERROR, outData));
            }


        } catch (Exception e) {
            outData = "apiClinkRecord HTTP请求调用错误，接口处理异常：" + e.getMessage();
            log.error(outData, e);
            return JSONObject.toJSONString(new Result(Result.ERROR, outData));
        }

        return result.toString();
    }

    // 文件上传NGS
    public static String uploadNGS(EliteBean eliteBean, String srcFileName) {

        File tempFile = new File(srcFileName.trim());

        String uploadResult = FileUploadUtil.uploadFile(KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") + "ngs/", KHDBConfig.getParamConfig(eliteBean, "NGS_fileServerKey"), "/record", tempFile);
        log.debug("文件上传NGS结果：" + uploadResult);

        net.sf.json.JSONObject resultJson = net.sf.json.JSONObject.fromObject(uploadResult);

        String code = resultJson.getString("code");
        if (code.equals("1")) {
            return resultJson.getJSONArray("value").getString(0);
        } else {
            return null;
        }
    }
}